import { constantRoutes } from '@/router'
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
// function hasPermission(roles, route) {
//   if (route.meta && route.meta.roles) {
//     return route.meta.roles.some(role => roles[0].includes(role))
//   } else {
//     return false
//   }
// }
export function getRouter(permission, level) {
  if (level === 1) { // 一级菜单Layout
    return {
      path: permission.path,
      component: Layout,
      children: [{
        path: '',
        component: (resolve) => require([`@/views/${permission.component}`], resolve),
        meta: {
          title: permission.name,
          icon: permission.icon
        }
      }]
    }
  } else { // 子菜单
    return {
      path: permission.path,
      component: (resolve) => require([`@/views/${permission.component}`], resolve),
      meta: {
        title: permission.name,
        icon: permission.icon
      }
    }
  }
}
export function initRoute(permission, level) { // 封装路由
  if (permission.children && permission.children.length > 0) { // 如果存在子节点
    const route = {
      path: permission.path,
      component: Layout,
      meta: {
        title: permission.name,
        icon: permission.icon
      },
      children: []
    }
    permission.children.forEach(child => { // 递归封装子节点
      route.children.push(initRoute(child, child.level))
    })
    return route
  } else { // 不存在子节点直接返回
    return getRouter(permission, level)
  }
}
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes) {
  const accessedRoutes = []
  if (routes) {
    routes.forEach(permission => {
      const routeNode = initRoute(permission, permission.level)
      accessedRoutes.push(routeNode) // push一个个封装好的路由数据
    })
  }
  return accessedRoutes
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

// nomalAuth 普通档案管理员 root root staff 员工 Manager 主管 Arch 兼职档案专业人员
const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes = []
      const result = roles
      accessedRoutes = filterAsyncRoutes(result)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
